<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="指标名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入指标名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="来源数据" prop="dataSource">-->
<!--        <el-input-->
<!--          v-model="queryParams.dataSource"-->
<!--          placeholder="来源数据"-->
<!--          clearable-->
<!--          style="width: 240px"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="创建时间" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd2"
          v-hasPermi="['system:indicator:add']"
        >新增一级指标</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="reset"
        >刷新缓存</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:indicator:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
              row-key="indicatorName"
              :default-expand-all="isExpandAll"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="指标名称" align="left" prop="indicatorName" />
      <el-table-column label="来源数据" align="center" prop="dataSource" :show-overflow-tooltip="true" />
      <el-table-column label="计算方式" align="center"  prop="calculationMethod" :show-overflow-tooltip="true">
        <template #default="scope">
          <div v-katex:auto >{{ scope.row.calculationMethod }}</div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:indicator:add']"
          >新增下级指标</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:indicator:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete2(scope.row)"
            v-hasPermi="['system:indicator:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>=0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 指标管理对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" append-to-body>
      <el-form ref="form" :model="indicatorForm" :rules="formRules" label-width="80px">
        <el-form-item label="指标名称" prop="indicatorName">
          <el-input v-model="indicatorForm.indicatorName" :placeholder="`请输入${isEdit ? '新' : ''}指标名称`" />
        </el-form-item>
        <el-form-item label="指标描述" prop="indicatorDescription">
          <el-input v-model="indicatorForm.indicatorDescription" :placeholder="`请输入${isEdit ? '新' : ''}指标描述`" />
        </el-form-item>
        <el-form-item label="来源数据" prop="dataSource">
          <el-input v-model="indicatorForm.dataSource" type="textarea" :placeholder="`请输入${isEdit ? '新' : ''}来源数据`"></el-input>
        </el-form-item>
        <el-form-item label="计算方式" prop="calculationMethod">
          <el-input v-model="indicatorForm.calculationMethod" type="textarea" :placeholder="`请输入${isEdit ? '新' : ''}计算方式`"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="indicatorForm.description" type="textarea" :placeholder="`请输入${isEdit ? '新' : ''}备注`"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getIndicatorsTree, search, delIndicator, addIndicator, updateIndicator } from "@/api/indicator/indicator";
  import 'katex/dist/katex.min.css';

  export default {
    name: "IndexManager",
    components: {},
    data() {
  return {
  // 遮罩层
  loading: true,
  // 显示搜索条件
  showSearch: true,
      // 表单数据
      indicatorForm: {
        id: null,
        indicatorName: '',
        indicatorLevel: 1,
        parentIndicatorId: null,
        calculationMethod: '',
        indicatorDescription: '',
        dataSource: '',
        description: ''
      },
      // 对话框状态
      dialogVisible: false,
      dialogTitle: '',
      // 表格数据
      dataList: [],
      selectedRows: [],
      multiple: true, // 控制删除按钮禁用状态（初始禁用）
      isEdit: false, // 标记是否为编辑状态
      // 是否处于搜索状态
      isSearch: false,
      // 查询参数
      queryParams: {
        name: null,
        time: [],
        dataSource: null,
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      isExpandAll: false,
      // 表单验证规则
      formRules: {
        indicatorName: [
          { required: true, message: "指标名称不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && !/^[A-Z]/.test(value)) {
                callback(new Error("指标名称必须以大写字母开头"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        // indicatorDescription: [
        //   { required: true, message: "指标描述不能为空", trigger: "blur" }
        // ]
      }
};
},
  created() {
  this.getList();
},
  methods: {
    // 表格选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.multiple = selection.length === 0; // 当没有选择项时禁用删除按钮
    },

    // 获取指标列表
    async getList() {
      // 如果处于搜索状态，则使用搜索接口
      if (this.isSearch) {
        await this.handleQuery();
        return;
      }
      
      try {
        this.loading = true;
        const response = await getIndicatorsTree(this.queryParams);
        this.dataList = response.rows;
        this.total = response.total || 0;
      } catch (error) {
        console.error('获取指标列表失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 搜索指标
    async handleQuery() {
      try {
        this.loading = true;
        // 标记处于搜索状态
        this.isSearch = true;
        const { name, time = [], dataSource, pageNum, pageSize } = this.queryParams;
        const [startTime, endTime] = time;
        const response = await search({
          name,
          startTime,
          endTime,
          dataSource,
          pageNum,
          pageSize
        });
        this.dataList = response.rows;
        this.total = response.total || 0;
      } catch (error) {
        console.error('搜索指标失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 重置表单
    reset() {
      this.queryParams = {
        name: null,
        time: [],
        dataSource: null,
        pageNum: 1,
        pageSize: 10
      };
      // 重置搜索状态
      this.isSearch = false;
      this.$refs.queryForm?.resetFields();
      this.getList();
    },

    // 取消操作
    cancel() {
      this.dialogVisible = false;
      this.reset();
    },

    // 新增指标
    handleAdd(row) {
      this.reset();
      this.isEdit = false;
      this.dialogTitle = "新增指标";

      if (row.id) {
        this.indicatorForm.parentIndicatorId = row.id;
        this.indicatorForm.indicatorLevel = row.indicatorLevel + 1;
      }

      this.dialogVisible = true;
    },

    // 新增一级指标
    handleAdd2() {
      this.reset();
      this.isEdit = false;
      this.dialogTitle = "新增一级指标";
      this.indicatorForm.indicatorLevel = 1;
      this.dialogVisible = true;
    },

    // 修改指标
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;
      this.dialogTitle = "修改指标";
      this.indicatorForm = { ...row };
      this.dialogVisible = true;
    },

    // 提交表单
    async submitForm() {
      try {
        const valid = await this.$refs.form.validate();
        if (!valid) return;

        // 检查指标名称是否已存在
        const isDuplicate = this.dataList.some(item =>
          item.indicatorName === this.indicatorForm.indicatorName &&
          (!this.isEdit || item.id !== this.indicatorForm.id)
        );

        if (isDuplicate) {
          this.$message.error('指标名称已存在，请使用其他名称');
          return;
        }

        const api = this.isEdit ? updateIndicator : addIndicator;
        await api(this.indicatorForm);

        this.$modal.msgSuccess(`${this.isEdit ? '修改' : '新增'}成功`);
        this.dialogVisible = false;
        this.getList();
      } catch (error) {
        console.error('提交表单失败:', error);
        this.$message.error(error.response?.data?.msg || '操作失败');
      }
    },

    // 删除指标
    async handleDelete() {
      const ids = this.selectedRows.map(item => item.id);
      if (ids.length === 0) {
        this.$message.warning("请先选择要删除的指标");
        return;
      }

      try {
        await this.$confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });

        await delIndicator(ids);
        this.$message.success("删除成功");
        this.getList();
        this.selectedRows = [];
      } catch (error) {
        if (error !== 'cancel') {
          const errorMsg = error.response?.data?.msg || error.message || '删除失败';
          this.$message.error(errorMsg.includes('删除失败') ? errorMsg : `删除失败: ${errorMsg}`);
          console.error('删除指标失败:', error);
        }
      }
    },

    // 删除单个指标
    async handleDelete2(row) {
      try {
        await this.$confirm("此操作将永久删除该指标, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });

        await delIndicator([row.id]);
        this.$message.success("删除成功");
        this.getList();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除指标失败:', error);
        }
      }
    }
  }
};
</script>


<style scoped>
</style>
